#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

export INSTALL_MOD_DIR := extra

KVERSION   ?= $(shell uname -r)
KERNEL_SRC ?= /lib/modules/$(KVERSION)
KERNEL_BUILD ?= $(shell if [ -d "/lib/modules/$(KVERSION)/build" ]; then echo "/lib/modules/$(KVERSION)/build"; else echo "/usr/src/linux-headers-$(KVERSION)"; fi)
MOD_SRC_DIR := $(shell pwd)
MODULE_DIRS := nh-4010
SERVICE_DIR := service
SYSTEM_DIR := etc/systemd/system
UTILS_DIR := utils

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

PACKAGE_PRE_NAME := sonic-platform-nexthop

%:
	dh $@ --with python3 --buildsystem=pybuild

override_dh_auto_build:
	set -e
	if [ ! -d "$(KERNEL_BUILD)" ]; then \
		echo "ERROR: Kernel build directory $(KERNEL_BUILD) not found. Cannot build kernel modules."; \
		exit 1; \
	fi
	(for mod in $(MODULE_DIRS); do \
		set -e; \
		make -C $(KERNEL_BUILD) M=$(MOD_SRC_DIR)/$${mod}/modules; \
		python3 setup.py bdist_wheel -d $(MOD_SRC_DIR); \
		echo "Finished making sonic_platform whl package"; \
	done)

override_dh_auto_test:
	python3 -m pytest

override_dh_usrlocal:
# Needed since we are installing files to /usr/local

override_dh_auto_install:
	set -e
	(for mod in $(MODULE_DIRS); do \
		set -e; \
		pkg_name=$(PACKAGE_PRE_NAME)-"$${mod#nh-}"; \
		dh_installdirs -p$${pkg_name} \
			$(KERNEL_SRC)/$(INSTALL_MOD_DIR); \
		dh_installdirs -p$${pkg_name} \
			/lib/systemd/system; \
		dh_installdirs -p$${pkg_name} \
			/usr/local/bin; \
		dh_installdirs -p$${pkg_name} \
			etc/udev/rules.d; \
		cp $(MOD_SRC_DIR)/$${mod}/modules/*.ko \
	  	debian/$${pkg_name}$(KERNEL_SRC)/$(INSTALL_MOD_DIR); \
		cp $(MOD_SRC_DIR)/$${mod}/$(SERVICE_DIR)/*.service \
			debian/$${pkg_name}/lib/systemd/system; \
		if [ -d $(MOD_SRC_DIR)/$${mod}/$(SYSTEM_DIR)/ ]; then \
		        mkdir -p debian/$${pkg_name}/$(SYSTEM_DIR)/; \
			cp -r $(MOD_SRC_DIR)/$${mod}/$(SYSTEM_DIR)/* \
				debian/$${pkg_name}/$(SYSTEM_DIR)/; \
		fi; \
		if [ -d $(MOD_SRC_DIR)/$${mod}/$(UTILS_DIR)/ ]; then \
			cp $(MOD_SRC_DIR)/$${mod}/$(UTILS_DIR)/* \
				debian/$${pkg_name}/usr/local/bin/; \
		fi; \
		if [ -d $(MOD_SRC_DIR)/$${mod}/udev/ ]; then \
			cp $(MOD_SRC_DIR)/$${mod}/udev/* \
				debian/$${pkg_name}/etc/udev/rules.d/; \
		fi; \
		if [ -d $(MOD_SRC_DIR)/$${mod}/bash_completion.d ]; then \
			dh_installdirs -p$${pkg_name} etc/bash_completion.d; \
			cp $(MOD_SRC_DIR)/$${mod}/bash_completion.d/* \
				debian/$${pkg_name}/etc/bash_completion.d/; \
		fi; \
		python3 setup.py install \
			--root=$(MOD_SRC_DIR)/debian/$${pkg_name} \
			--install-layout=deb; \
	done)

override_dh_clean:
	set -e
	dh_clean
	(for mod in $(MODULE_DIRS); do \
		set -e; \
		if [ -d "$(KERNEL_BUILD)" ]; then \
			make -C $(KERNEL_BUILD) M=$(MOD_SRC_DIR)/$${mod}/modules clean; \
		fi; \
		echo $(MOD_SRC_DIR); \
		rm -f $(MOD_SRC_DIR)/*.whl; \
	done)
